/**
 * 用户相关API接口
 */

// API基础配置
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8086';

// 通用请求函数（兼容 code 为 0 或 200 的业务成功）
const request = async (url: string, options: RequestInit = {}) => {
  const response = await fetch(`${API_BASE_URL}${url}`, {
    headers: {
      'Content-Type': 'application/json',
      ...options.headers,
    },
    credentials: 'include',
    ...options,
  });

  const result = await response.json().catch(() => ({ code: response.status, message: response.statusText }));

  // HTTP错误优先
  if (!response.ok) {
    throw new Error(result.message || `HTTP ${response.status}`);
  }

  // 业务状态码判断
  if (typeof result.code !== 'undefined' && !(result.code === 0 || result.code === 200)) {
    throw new Error(result.message || '请求失败');
  }

  return result;
};

// 注册请求体类型
export interface RegisterUserProfile {
  nickName?: string;
  gender?: number;
  avatar?: string;
  address?: string;
  email?: string;
  idCard?: string;
  eduDegree?: string;
  graduateSchool?: string;
  specialty?: string;
  rank?: string;
  subject?: string;
  phone?: string;
}

export interface RegisterUserPayload {
  username: string;
  password: string;
  enable: boolean;
  profile: RegisterUserProfile;
  roleIds: number[];
}

export const userApi = {
  // 注册用户（调用后端 UserController.create -> POST /user）
  register: (data: RegisterUserPayload): Promise<any> => {
    return request('/user', {
      method: 'POST',
      body: JSON.stringify(data),
    });
  },
};

export default userApi;